package com.toddding.controller;

import cn.hutool.core.util.StrUtil;
import com.toddding.domain.User;
import com.toddding.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.RequestMapping;

import javax.servlet.http.HttpSession;

@RequestMapping("user")
@Controller
public class UserController {

    @Autowired
    private UserService userService;

    @RequestMapping("login.do")
    public String login(String loginName, String loginPwd, String checkCode, HttpSession httpSession) {
        // 校验验证码
        Object code = httpSession.getAttribute("code");
        if (code == null || !StrUtil.equals(code.toString(), checkCode)) {
            return "redirect:/index.jsp";
        }
        //根据账号密码查询用户
        User user = userService.queryUser(loginName, loginPwd);
        if (user == null) {
            return "redirect:/index.jsp";
        }
        httpSession.setAttribute("user", user);
        return "redirect:/main.jsp";
    }

    /**
     * 跳转到修改密码页面
     *
     * @param folderId
     * @param model
     * @return
     */
    @RequestMapping("toUpdatePwd.do")
    public String toUpdate(Integer folderId, Model model) {
        return "redirect:/view/user/updatePwd.jsp";
    }

    /**
     * 修改密码
     *
     * @param mpass       原密码
     * @param newpass     新密码
     * @param httpSession
     * @return
     */
    @RequestMapping("updatePwd.do")
    public String updatePwd(String mpass, String newpass, HttpSession httpSession) {
        User user = (User) httpSession.getAttribute("user");
        String oldPwd = user.getLoginPwd();
        if (!mpass.equals(oldPwd)) {
            return "redirect:/view/user/updatePwd.jsp";
        }
        User updateUser = new User(user.getUserId(), user.getUserName(), user.getLoginName(), newpass);
        int count = this.userService.updatePwd(updateUser);
        if (count > 0) {
            httpSession.invalidate(); // 销毁 session
            return "redirect:/toIndex.jsp";
        }
        return "redirect:/view/user/updatePwd.jsp";
    }

}
